<template>
	<view class="container">
		<h-icon class-name="login_logo" src="login/logo" mode="heightFix" type="jpg"></h-icon>
		<view class="title b-b">陪诊小程序</view>
		<view class="info">
			<view class="tit">登录后将获得以下权限</view>
			<view class="xx">获得您的公开信息（昵称、头像等）</view>
		</view>
		<!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
		<button
			class="btn-link"
			open-type="getPhoneNumber"
			@getphonenumber="getPhoneNumber"
			withCredentials="true"
			:disabled="logining"
		>确认登录</button>
		<view class="login_tip">点击即表示同意陪诊小程序
			<text @click="navTo('/userPages/legal')">《用户协议》</text>
		</view>
		<uni-pop
			type="confirm"
			v-model="popData.isShow"
			:title="popData.title">
			<template slot="commit">
				<button
				class="commit-btn yes"
				@click="wxLogin">授权</button>
			</template>
		</uni-pop>
	</view>
</template>

<script>
	import { getWeixinCode } from './login'
	import { mapMutations } from 'vuex';
	export default{
		data(){
			return {
				form: {},
				logining: false,
				params: {
          iv: '',
					encrypted: '',
          sessionKey: '',
          openId: ''
        },
				popData:{
					isShow: false,
					title:`请允许获取用户信息授权`
				}, // 弹窗信息
				firstLoad: true // 是否第一次调用
			}
		},
		onLoad() {
			uni.removeStorageSync('openId')
			uni.removeStorageSync('sessionKey')
			uni.removeStorageSync('unionId')
      this.pageInit()
		},
		onShow(){
			getApp().globalData.orderRefresh = true // 是否刷新
		},
		methods: {
			...mapMutations(['login','logout']),
			navTo(url){
				uni.navigateTo({ url })
			},
       pageInit() {
        wx.checkSession({
          success: async (res) => {
            console.log("处于登录态")
            this.params.openId = uni.getStorageSync('openId')
            this.params.sessionKey = uni.getStorageSync('sessionKey')
						this.params.unionId = uni.getStorageSync('unionId')
						if(!this.params.openId||!this.params.sessionKey){
							this.getSessionKey()
						}
          },
          fail: (res) => {
            console.log("需要重新登录")
            this.getSessionKey()
          }
        })
      },
      async getSessionKey() {
        const js_code = await getWeixinCode()
				
        const {code,result}  = await this.$apis.getSessionKey({code: js_code})
				console.log('sessionKey、openId'+JSON.stringify(result))
        if(code!=200) return
        const {sessionKey,openId,unionId} = result
        this.params.openId = openId
        this.params.sessionKey = sessionKey
				this.params.unionId = unionId
        uni.setStorageSync('openId', openId)
        uni.setStorageSync('sessionKey', sessionKey)
				uni.setStorageSync('unionId', unionId)
      },
			async getPhoneNumber(e) {
				if (!e.detail.encryptedData) {
					uni.showToast({
						icon: 'none',
						title: '请允许获取用户手机号授权',
					})
					return
				}
				const { encryptedData,iv } = e.detail
        this.params.encrypted = encryptedData
        this.params.iv = iv
				this.toLogin(this.params)
			},
			wxLogin() {
				uni.getUserProfile({  
          desc: "用于完善用户资料",  
          success: ({ userInfo }) => {  
						let form = {
							userId:this.users.userId,
							nickName: userInfo.nickName,
							userIcon: userInfo.avatarUrl
						}
						this.$apis.postApi('/user/updUser',form).then(({code,message}) => {
							if(code==200){
								this.popData.isShow = false
								this.users = {...this.users,...form}
								this.loginSuccess()
							} else {
								this.$api.msg(message)
							}
						})
          }  
        })
				
			},
			async toLogin(form) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				this.logining = true;
				const {code,result,message} = await this.$apis.getLogin(form)
				uni.hideLoading()
				this.logining = false;
				if (code == 200) {
					this.users = result
					if(result.userIcon){
						this.loginSuccess()
					} else {
						this.popData = {
							isShow: true,
							title:`请允许获取用户信息授权`
						}
					}
				} else {
					console.log('登录失败，再次请求')
					uni.removeStorageSync('openId')
					uni.removeStorageSync('sessionKey')
					uni.removeStorageSync('unionId')
					if(this.firstLoad) {
						await this.getSessionKey()
						this.toLogin(this.params)
					} else {
						this.$api.msg(message)
					}
					this.firstLoad = false
				}
			},
			async loginSuccess(){
				this.login(this.users)
				uni.navigateBack()
			}
		}
	}
</script>

<style lang='scss' scoped>
	.container{
		position:relative;
		height: calc(100vh - 40upx);
		overflow: hidden;
		background: #fff;
		border-radius: 16px;
		margin: 20upx;
		padding: 0 36upx;
	}
	/deep/ .login_logo{
		width: 128upx;
		height: 128upx;
		margin: 70upx auto 0;
		display: block;
		background: #4083F0;
		border-radius: 16upx;
		border: 1px solid #4083F0;
	}
	.title{
		text-align: center;
		font-size: 30upx;
		position: relative;
		padding: 25upx 0 50upx;
	}
	.info{
		padding: 40upx 0 70upx;
		.tit{
			font-size: 30upx;
		}
		.xx{
			font-size: 24upx;
			color: #666666;
			margin-top: 18upx;
		}
	}
	.login_tip{
		margin: 22upx 0;
		text-align: center;
		font-size: 26upx;
		text{
			color: #FB8B05;
		}
	}
	
	.confirm-btn{
		width: 610upx;
		height: 88upx;
		background: linear-gradient(0deg, #FB8B05, #FF5502);
		border-radius: 10upx;
		font-weight: 500;
		color: #fff;
		font-size: $font-lg;
		&:after{
			display: none;
		}
	}

</style>
